import { Buffer } from 'buffer';
import { ControlMessage, ControlMessageInterface } from './ControlMessage';
import { BasePlayer } from '../player/BasePlayer';

// 扩展ControlMessageInterface，添加广播所需的属性
export interface BroadcastControlMessageInterface extends ControlMessageInterface {
    isBroadcast: boolean;
    sourcePlayerId: string | number; // 源云手机唯一标识
}

export class BroadcastControlMessage extends ControlMessage {
    public readonly isBroadcast: boolean = true;
    public readonly sourcePlayer: BasePlayer;

    constructor(
        sourcePlayer: BasePlayer,
        originalMessage: ControlMessage
    ) {
        // 调用父类构造函数，传递原始消息的类型
        super(originalMessage.type);
        this.sourcePlayer = sourcePlayer;
    }

    /**
     * 转换为Buffer，在原始消息基础上添加广播标识
     */
    public toBuffer(): Buffer {
        // 获取原始消息的Buffer
        const originalBuffer = this.getOriginalMessageBuffer();
        
        // 创建包含广播信息的Buffer
        // 这里假设前4个字节存储广播标识，后续存储原始消息数据
        const broadcastBuffer = Buffer.alloc(originalBuffer.length + 4);
        broadcastBuffer.writeUInt32BE(1, 0); // 1表示这是广播消息
        originalBuffer.copy(broadcastBuffer, 4);
        
        return broadcastBuffer;
    }

    // /**
    //  * 转换为字符串表示
    //  */
    // public toString(): string {
    //     return `BroadcastControlMessage(type: ${this.type}, sourcePlayer: ${this.sourcePlayer.id}, isBroadcast: true)`;
    // }

    // /**
    //  * 转换为JSON对象
    //  */
    // public toJSON(): BroadcastControlMessageInterface {
    //     return {
    //         ...super.toJSON(),
    //         isBroadcast: this.isBroadcast,
    //         sourcePlayerId: this.sourcePlayer.id // 假设BasePlayer有id属性作为唯一标识
    //     };
    // }

    /**
     * 获取原始消息的Buffer（通过反射获取私有方法，实际项目中可能需要调整）
     */
    private getOriginalMessageBuffer(): Buffer {
        // 这里需要根据实际情况获取原始消息的Buffer
        // 如果originalMessage的toBuffer()是public的，可以直接调用
        // 这里仅作示例
        return Buffer.alloc(0);
    }
}
